{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.ns-discount { display: flex; justify-content: space-between; height: 34px; line-height: 34px; padding: 5px 15px; background-color: #F6FBFD; border: 1px dashed #BCE8F1; }
	.ns-exchange-type {padding: 0 20px; position: relative;}
	.ns-exchange-type:hover {border: 1px solid #ff8143;}
	.ns-exchange-selected {border: 1px solid #ff8143;}
	.ns-exchange-selected:after {
		content: "";
		display: inline-block;
		width: 20px;
		height: 20px;
		background-image: url(__STATIC__/img/selected.png);
		position: absolute;
		bottom: 0;
		right: 0;
	}
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
	<div class="layui-colla-item">
		<h2 class="layui-colla-title">操作提示</h2>
		<ul class="layui-colla-content layui-show">
			<li>满减活动包括店铺所有商品，活动时间不能和已有活动重叠</li>
			<li>每添加一个规则都需点击确定规则设置按钮，生成一条规则，提交之后才可成功添加</li>
			<li>点击确定规则设置按钮生成的规则都有一个删除按钮，如不需要该条规则点击删除按钮即可删除</li>
		</ul>
	</div>
</div>

<div class="layui-form ns-form">

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>优惠券名称：</label>
		<div class="layui-input-block">
			<input type="text" name="coupon_name" value="{$coupon_type_info.coupon_name}" lay-verify="required" autocomplete="off" class="layui-input ns-len-long">
		</div>
	</div>

	<div class="layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label">优惠券类型：</label>
			<div class="layui-input-block">
				<button class="layui-btn layui-btn-primary ns-exchange-type {if $coupon_type_info.type == 'reward'} ns-exchange-selected {/if}" data-status="reward">满减</button>
				<button class="layui-btn layui-btn-primary ns-exchange-type {if $coupon_type_info.type == 'discount'} ns-exchange-selected {/if}" data-status="discount">折扣</button>
				<input type="hidden" name="type" value="{$coupon_type_info.type}">
			</div>
		</div>
	</div>

		<div class="layui-form-item" id="coupon_type">
			{if $coupon_type_info.type == 'reward'}
			<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="money" value="{$coupon_type_info.money}" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">元</span>
			</div>
			<div class="ns-word-aux">
				<p>价格不能小于0，可保留两位小数</p>
			</div>
			{else /}
			<label class="layui-form-label"><span class="required">*</span>优惠券折扣：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="discount" min="1" value="{$coupon_type_info.discount}" lay-verify="required|fl" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">折</span>
			</div>
			<div class="ns-word-aux">
				<p>优惠券折扣不能小于1折，且不可大于9.9折，可保留两位小数</p>
			</div>
			{/if}
		</div>

		{if $coupon_type_info.type == 'discount'}
		<div class="layui-form-item discount_limit">
			<label class="layui-form-label">最多优惠：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="discount_limit" min=0 value="{$coupon_type_info.discount_limit}" lay-verify="number|int" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">元</span>
			</div>
		</div>
		{/if}

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>发放数量：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="count" min=0 value="{$coupon_type_info.count}" lay-verify="required|number|int" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">张</span>
			</div>
			<div class="ns-word-aux">
				<p>数量不能小于0，且必须为整数</p>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>最大领取数量：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="max_fetch" min=0 value="{$coupon_type_info.max_fetch}" lay-verify="required|number|int|max" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">张</span>
			</div>
			<div class="ns-word-aux">
				<p>数量不能小于0，且必须为整数；设置为0时，可无限领取</p>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>满多少元可以使用：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="at_least" value="{$coupon_type_info.at_least}" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">元</span>
			</div>
			<div class="ns-word-aux">
				<p>价格不能小于0，可保留两位小数</p>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label img-upload-lable">优惠券图片：</label>
			<div class="layui-input-inline img-upload">
				<input type="hidden" class="layui-input" name="image" value="{$coupon_type_info.image}" />
				<div class="upload-img-block icon">
					<div class="upload-img-box" id="couponImg">
						{if condition="$coupon_type_info.image"}
						<img src="{:img($coupon_type_info.image)}" />
						{else/}
						<div class="ns-upload-default">
							<img src="SHOP_IMG/upload_img.png" />
							<p>点击上传</p>
						</div>
						{/if}
					</div>
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">是否允许直接领取：</label>
			<div class="layui-input-block">
				<input type="checkbox" name="is_show" min=0 lay-filter="" value="1" lay-skin="switch" {if condition="$coupon_type_info.is_show == 1"}checked{/if} />
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">有效期类型：</label>
			<div class="layui-input-block">
				<input type="radio" name="validity_type" value="0" lay-filter="filter" title="固定时间" {if condition="$coupon_type_info.validity_type == 0"}checked{/if}>
				<input type="radio" name="validity_type" value="1" lay-filter="filter" title="领取之日起" {if condition="$coupon_type_info.validity_type == 1"}checked{/if}>
			</div>
		</div>

		<div class="layui-form-item ns-end-time">
			<label class="layui-form-label ">活动结束时间：</label>
			<div class="layui-input-block">
				<input type="text" name="end_time" value="{:date('Y-m-d H:i:s', $coupon_type_info.end_time)}" lay-verify="time" id="end_time" class="layui-input ns-len-mid" readonly>
			</div>
		</div>

		<div class="layui-form-item ns-fixed-term">
			<label class="layui-form-label">领取后几天有效：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="fixed_term" value="{$coupon_type_info.fixed_term}" lay-verify="days" autocomplete="off" class="layui-input ns-len-short">
				</div>
				<span class="layui-form-mid">天</span>
			</div>
			<div class="ns-word-aux">
				<p>不能小于0，且必须为整数</p>
			</div>
		</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动商品：</label>
		<div class="layui-input-block">
			<input type="radio" name="goods_type" lay-filter="goods_type" value="1" title="全部商品参与" {if $coupon_type_info.goods_type == 1} checked {/if}>
			<input type="radio" name="goods_type" lay-filter="goods_type" value="2" title="指定商品参与" {if $coupon_type_info.goods_type == 2} checked {/if}>
		</div>
	</div>

	{if $coupon_type_info.goods_type == 1}
	<div class="layui-form-item goods_list" style="display:none">
		{else /}
		<div class="layui-form-item goods_list">
			{/if}
			<label class="layui-form-label"></label>
			<div class="layui-input-block">
				<table id="selected_sku_list"></table>
				<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
			</div>
		</div>
		<input type="hidden" name="goods_ids">

		<div class="ns-form-row">
			<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>

		<input type="hidden" name="site_id" value="{$coupon_type_info.site_id}" />
		<input type="hidden" name="coupon_type_id" value="{$coupon_type_info.coupon_type_id}" />
	</div>

	<!-- 操作 -->
	<script type="text/html" id="operation">
		<div class="ns-table-btn">
			<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
		</div>
	</script>
	{/block}
	{block name="script"}
	<script>

        var validity_type = $("input[name='validity_type']:checked").val();
        if (validity_type == 0) {
            $('.ns-end-time').removeClass('layui-hide');
            $('.ns-fixed-term').addClass('layui-hide');
        } else {
            $('.ns-fixed-term').removeClass('layui-hide');
            $('.ns-end-time').addClass('layui-hide');
        }

        var delRule, selectedGoodsId = [], goods_id=[];
        var goods_list = {:json_encode($coupon_type_info.goods_list, JSON_UNESCAPED_UNICODE)};

        $.each(goods_list, function(index, item) {
            var id = item.goods_id;
            selectedGoodsId.push(id);
            goods_id.push(id);
        });
        $("input[name='goods_ids']").val(goods_id.toString());

        layui.use(['form', 'laydate', 'upload'], function() {
            var form = layui.form,
                upload = layui.upload,
                laydate = layui.laydate,
                repeat_flag = false; //防重复标识

                form.render();

			// 时间模块
            laydate.render({
                elem: '#end_time', //指定元素
                type: 'datetime'
            });

            renderTable(goods_list); // 初始化表格

            //监听活动商品类型
            form.on('radio(goods_type)', function(data){
                var value = data.value;

                if(value == 1){
                    $(".goods_list").hide();
                }
                if(value == 2){
                    $(".goods_list").show();
                }
            });

			// 监听单选按钮
            form.on('radio(filter)', function(data) {
                if (data.value == 0) {
                    $('.ns-end-time').removeClass('layui-hide');
                    $('.ns-fixed-term').addClass('layui-hide');
                } else {
                    $('.ns-fixed-term').removeClass('layui-hide');
                    $('.ns-end-time').addClass('layui-hide');
                }
            });
            /**
             * 表单验证
             */
            form.verify({
                days: function(value) {
                    if (value == '') {
                        return;
                    }
                    if (value%1 != 0) {
                        return '请输入整数';
                    }
                },
                number: function (value) {
                    if (value < 0) {
                        return '请输入不小于0的数!'
                    }
                },
                int: function (value) {
                    if (value%1 != 0) {
                        return '请输入整数!'
                    }
                    if (value < 0) {
                        return '请输入大于0的数!'
                    }
                },
                money: function (value) {
                    var arrMen = value.split(".");
                    var val = 0;
                    if (arrMen.length == 2) {
                        val = arrMen[1];
                    }
                    if (val.length > 2) {
                        return '保留小数点后两位'
                    }
                },
                time: function(value) {
                    var now_time = (new Date()).getTime();
                    var end_time = (new Date(value)).getTime();
                    if (now_time > end_time) {
                        return '结束时间不能小于当前时间!'
                    }
                },
                max: function(value) {
                    var _count = $("input[name=count]").val();

                    if (parseFloat(value) > parseFloat(_count)) {
                        return '最大领取数量不能超过发放数量!';
                    }
                },
                fl: function(value, item) {
                    var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                    str = str.substring(0, str.length - 1);

                    if (value < 1) {
                        return str + "不能小于1折";
                    }

                    if (value > 9.9) {
                        return str + "不能大于9.9折";
                    }

                    var arrMen = value.split(".");
                    var val = 0;
                    if (arrMen.length == 2) {
                        val = arrMen[1];
                    }
                    if (val.length > 2) {
                        return str + "最多可保留两位小数";
                    }
                }
            });

            // 图片上传
            var uploadInst = upload.render({
                elem: '#couponImg',
                url: ns.url("shop/upload/image"),
                done: function(res) {
                    if (res.code >= 0) {
                        $("input[name='image']").val(res.data.pic_path);
                        $("#couponImg").html("<img src=" + ns.img(res.data.pic_path) + " >");
                    }
                    return layer.msg(res.message);
                }
            });

            /**
             * 监听提交
             */
            form.on('submit(save)', function(data) {

                if(data.field.goods_type != 1){
                    if(data.field.goods_ids == ''){
                        layer.msg("请选择商品");
                        return;
                    }
                }
                if (repeat_flag) return;
                repeat_flag = true;

                $.ajax({
                    url: ns.url("coupon://shop/coupon/edit"),
                    data: data.field,
                    dataType: 'JSON',
                    type: 'POST',
                    success: function(res) {
                        repeat_flag = false;

                        if (res.code == 0) {
                            layer.confirm('编辑成功', {
                                title:'操作提示',
                                btn: ['返回列表', '继续操作'],
                                yes: function(){
                                    location.href = ns.url("coupon://shop/coupon/lists")
                                },
                                btn2: function() {
                                    location.reload();
                                }
                            });
                        }else{
                            layer.msg(res.message);
                        }
                    }
                });
            });

            delRule = function(obj) {
                $(obj).parent().parent().remove();
            };

            $(".ns-exchange-type").click(function() {
                $(this).addClass("ns-exchange-selected");
                $(this).siblings("button").removeClass("ns-exchange-selected");

                var type = $(this).attr('data-status');

                var current_type = $("input[name='type']").val();
                if(current_type == type){
                    return false;
                }

                $("input[name='type']").val(type);

                var html = '';
                if(type == 'reward'){
                    html += '<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>' +
                        '<div class="layui-input-block">' +
                        '<div class="layui-input-inline">' +
                        '<input type="number" name="money" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input ns-len-short">' +
                        '</div>' +
                        '<span class="layui-form-mid">元</span>' +
                        '</div>' +
                        '<div class="ns-word-aux">' +
                        '<p>价格不能小于0，可保留两位小数</p>' +
                        '</div>';

                    $('.discount_limit').remove();
                }

                if(type == 'discount'){
                    html += '<label class="layui-form-label"><span class="required">*</span>优惠券折扣：</label>' +
                        '<div class="layui-input-block">' +
                        '<div class="layui-input-inline">' +
                        '<input type="number" name="discount" min="1" lay-verify="required|fl" autocomplete="off" class="layui-input ns-len-short">' +
                        '</div>' +
                        '<span class="layui-form-mid">折</span>' +
                        '</div>' +
                        '<div class="ns-word-aux">' +
                        '<p>优惠券折扣不能小于1折，且不可大于9.9折，可保留两位小数</p>' +
                        '</div>';

                    var discount_limit = '';
                    discount_limit += '<div class="layui-form-item discount_limit">' +
                        '<label class="layui-form-label">最多优惠：</label>' +
                        '<div class="layui-input-block">' +
                        '<div class="layui-input-inline">' +
                        '<input type="number" name="discount_limit" min="0" lay-verify="number|int" autocomplete="off" class="layui-input ns-len-short">' +
                        '</div>' +
                        '<span class="layui-form-mid">元</span>' +
                        '</div>' +
                        '</div>';
                    $('#coupon_type').after(discount_limit);

                }
                $('#coupon_type').html(html);
            });
        });

        // 表格渲染
        function renderTable(goods_list) {
            //展示已知数据
            table = new Table({
                elem: '#selected_sku_list',
                cols: [
                    [{
                        field: 'goods_name',
                        title: '商品名称',
                        unresize: 'false',
                        width: '50%'
                    }, {
                        field: 'price',
                        title: '商品价格(元)',
                        unresize: 'false',
                        align: 'right',
                        width: '20%',
                        templet: function(data) {
                            return '￥' + data.price;
                        }
                    }, {
                        field: 'goods_stock',
                        title: '库存',
                        unresize: 'false',
                        align: 'center',
                        width: '20%'
                    }, {
                        title: '操作',
                        toolbar: '#operation',
                        unresize: 'false',
                        width: '10%'
                    }],
                ],
                data: goods_list,
            });
        }

        // 删除选中商品
        function delGoods(id) {
            var i, j;
            $.each(goods_list, function(index, item) {
                var goods_id = item.goods_id;

                if (id == goods_id) {
                    i = index;
                }
            })
            goods_list.splice(i, 1);
            renderTable(goods_list);

            $.each(selectedGoodsId, function(index, item) {
                if (id == item) {
                    j = index;
                }
            })
            selectedGoodsId.splice(j, 1);
            goods_id = selectedGoodsId;
            $("input[name='goods_ids']").val(goods_id.toString());
        }

        function addGoods(){
            goodsSelect(function (res) {
				if (!res.length) return false;
                for(var i=0;i<res.length;i++) {
                    goods_id.push(res[i].goods_id);
                    goods_list.push(res[i]);
                }
                renderTable(goods_list);
                $("input[name='goods_ids']").val(goods_id.toString());
                selectedGoodsId = goods_id;

            }, selectedGoodsId, {mode: "spu"});
        }

        function back() {
            location.href = ns.url("coupon://shop/coupon/lists");
        }
	</script>
	{/block}